<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/6/12
 * Time: 9:48
 */

namespace app\api\controller;


use think\Db;

class Aftersale extends Base
{
    public $after_num;//售后单号
    public $after_time;//年-月-日 时:分:秒
    public $user_id;//用户ID
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->after_num = date('YmdHis') . rand(000000, 999999);
        $this->after_time = date('Y-m-d H:i:s');
        $this->user_id = input('user_id');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }
    }
    
    /**
     * 换货说明
     * @return \think\response\Json
     */
    public function saleExplain(){
        $explain = Db::table('up_about')->where('id', 5)->value('content');
        if($explain){
            return json(['status' => 200, 'msg' => $explain]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 退货原因
     * @return \think\response\Json
     */
    public function returnReason(){
        $return = Db::table('up_return')
            ->field('exchange_id, exchange_name')
            ->order('exchange_add_time desc')
            ->select();
        if($return){
            return json(['status' => 200, 'msg' => $return]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 换货原因
     * @return \think\response\Json
     */
    public function exchangeReason(){
        $exchange = Db::table('up_exchange')
            ->field('exchange_id, exchange_name')
            ->order('exchange_add_time desc')
            ->select();
        if($exchange){
            return json(['status' => 200, 'msg' => $exchange]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 商品选择列表
     * @return \think\response\Json
     * oi_id  订单详情ID
     */
    public function choosedGoods(){
        $oi_id = input('oi_id');
        $list = Db::table('up_order_info')
            ->join('up_good_spec', 'spec_id = oi_spec_id', 'left')
            ->where('oi_id', $oi_id)
            ->field('oi_id, oi_good_id, oi_price, oi_num, oi_good_name, oi_good_thumb, oi_type, 
            oi_after_status, spec_name, oi_order_id')
            ->find();
        $order = Db::table('up_order')
            ->join('up_area ua1', 'ua1.district_id = order_sheng', 'left')
            ->join('up_area ua2', 'ua2.district_id = order_shi', 'left')
            ->join('up_area ua3', 'ua3.district_id = order_qu', 'left')
            ->where('order_id', $list['oi_order_id'])
            ->field('order_name, order_address, order_phone, ua1.district as sheng, 
            ua2.district as shi, ua3.district as qu')
            ->find();
        $list['order_name'] = $order['order_name'];
        $list['order_address'] = $order['sheng'] . $order['shi'] . $order['qu'] . $order['order_address'];
        $list['order_phone'] = $order['order_phone'];
        return json(['status' => 200, 'msg' => $list]);
    }
    
    /**
     * 提交退货----只有人民币可以退
     * @return \think\response\Json
     * oi_id             订单详情ID
     * after_return_id   退货原因
     * after_reason      退货说明
     */
    public function saleReturn(){
        $oi_id = input('oi_id');
        $after_return_id = input('after_return_id');//退货原因
        $after_reason = trim(input('after_reason'), ' ');//退货说明
        $orderInfo = Db::table('up_order_info')
            ->where('oi_id', $oi_id)
            ->field('oi_order_id, oi_good_id')
            ->find();
        $order = Db::table('up_order')->where('order_id', $orderInfo['oi_order_id'])->field('order_number')->find();
        Db::startTrans();
        try{
            $user_phone = Db::table('up_my_address')
                ->where('address_user_id', $this->user_id)
                ->where('is_default', 2)
                ->value('address_phone');
            
            $data = [
                'oi_after_status' => 2,
                'after_return_id' => $after_return_id,
                'after_reason' => $after_reason,
                'after_num' => $this->after_num,
                'after_order_num' => $order['order_number'],
                'after_time' => $this->after_time,
                'after_user_phone' => $user_phone,
                'after_status' => 1,
                'oi_user_id' => $this->user_id, //oi_user_id为了同步之前用户的数据
            ];
            //修改订单详情表
            Db::table('up_order_info')->where('oi_id', $oi_id)->update($data);
            
            //修改订单表状态为申请售后
            Db::table('up_order')->where('order_id', $orderInfo['oi_order_id'])->setField('order_after', 2);
            
            //如果是拒绝后的再次提交，则要删除时间轴表里之前的数据
            $is_have = Db::table('up_after_sale_time')->where('ast_after_oi_id', $oi_id)->find();
            if($is_have){
                Db::table('up_after_sale_time')->where('ast_after_oi_id', $oi_id)->delete();
            }
            
            //插入时间轴表
            $time_data = [
                'ast_after_oi_id' => $oi_id,
                'ast_after_time' => $this->after_time,
                'ast_after_content' => '您的退货申请已提交，请等待平台审核',
            ];
            Db::table('up_after_sale_time')->insert($time_data);
            
            Db::commit();
            $res = 1;
        }catch(\Exception $e){
            Db::rollback();
            $res = 2;
        }
        if($res == 1){
            return json(['status' => 200, 'msg' => '提交成功']);
        }else{
            return json(['status' => 0, 'msg' => '提交失败']);
        }
    }
    
    /**
     * 提交换货------金币/人民币都可以
     * @return \think\response\Json
     * oi_id                  订单详情ID
     * after_exchange_id      换货原因ID
     * after_reason           换货说明
     * after_spec_id          新的规格
     */
    public function saleChange(){
        $oi_id = input('oi_id');
        $after_exchange_id = input('after_exchange_id'); //换货原因ID
        $after_reason = input('after_reason'); //换货说明
        $after_spec_id = input('after_spec_id'); //人民币换货时选择的新规格
        $orderInfo = Db::table('up_order_info')
            ->field('oi_order_id, oi_good_id, oi_type')
            ->where('oi_id', $oi_id)
            ->find();
        $order = Db::table('up_order')->where('order_id', $orderInfo['oi_order_id'])->field('order_number')->find();
        Db::startTrans();
        try{
            $user_phone = Db::table('up_my_address')
                ->where('address_user_id', $this->user_id)
                ->where('is_default', 2)
                ->value('address_phone');
            
            $data = [
                'oi_after_status' => 3,
                'after_exchange_id' => $after_exchange_id,
                'after_reason' => $after_reason,
                'after_status' => 1,
                'after_num' => $this->after_num,
                'after_order_num' => $order['order_number'],
                'after_time' => $this->after_time,
                'after_user_phone' => $user_phone,
                'oi_user_id' => $this->user_id, //oi_user_id为了同步之前用户的数据
            ];
            if($orderInfo['oi_type'] == 1){ //人民币
                if($after_spec_id != ''){
                    $data ['after_spec_id'] = $after_spec_id;
                }else{
                    $spec = Db::table('up_order_info')->where('oi_id', $oi_id)->value('oi_spec_id');
                    $data['after_spec_id'] = $spec;
                }
            }
            //修改订单详情表
            Db::table('up_order_info')->where('oi_id', $oi_id)->update($data);
            
            //修改订单表状态为申请售后
            Db::table('up_order')->where('order_id', $orderInfo['oi_order_id'])->setField('order_after', 2);
            
            //如果是拒绝后的再次提交，则要删除时间轴表里之前的数据
            $is_have = Db::table('up_after_sale_time')->where('ast_after_oi_id', $oi_id)->find();
            if($is_have){
                Db::table('up_after_sale_time')->where('ast_after_oi_id', $oi_id)->delete();
            }
            
            //插入时间轴表
            $time_data = [
                'ast_after_oi_id' => $oi_id,
                'ast_after_time' => $this->after_time,
                'ast_after_content' => '您的换货申请已提交，请等待平台审核',
            ];
            Db::table('up_after_sale_time')->insert($time_data);
            
            Db::commit();
            $res = 1;
        }catch(\Exception $e){
            Db::rollback();
            $res = 2;
        }
        if($res == 1){
            return json(['status' => 200, 'msg' => '提交成功']);
        }else{
            return json(['status' => 0, 'msg' => '提交失败']);
        }
    }
    
    /**
     * 撤销退/换货申请
     * @return \think\response\Json
     * oi_id   订单详情ID
     */
    public function rollbackSale(){
        $oi_id = input('oi_id');
        $orderInfo = Db::table('up_order_info')
            ->where('oi_id', $oi_id)
            ->field('oi_order_id, oi_good_id')
            ->find();
        Db::startTrans();
        try{
            //修改订单详情表状态
            $update = [
                'oi_after_status' => 1,
                'after_return_id' => null,
                'after_exchange_id' => null,
                'after_reason' => null,
                'after_status' => -1,
                'after_num' => null,
                'after_order_num' => null,
                'after_time' => null,
                'after_spec_id' => null,
                'after_user_phone' => null
            ];
            Db::table('up_order_info')->where('oi_id', $oi_id)->update($update);
            
            //查询该订单是否还有在售后中的商品，如果没有，修改订单表和订单详情表的状态
            $num = Db::table('up_order_info')
                ->where('oi_good_id', $orderInfo['oi_good_id'])
                ->where('oi_after_status', 'neq', 1)
                ->count('oi_id');
            if($num == 0){
                //修改订单表状态为未申请售后
                Db::table('up_order')->where('order_id', $orderInfo['oi_good_id'])->setField('order_after', 1);
            }
            
            //删除售后时间轴表数据
            Db::table('up_after_sale_time')->where('ast_after_oi_id', $oi_id)->delete();
            
            Db::commit();
            $res = 1;
        }catch(\Exception $e){
            Db::rollback();
            $res = 2;
        }
        if($res == 1){
            return json(['status' => 200, 'msg' => '撤销成功']);
        }else{
            return json(['status' => 0, 'msg' => '撤销失败']);
        }
    }
    
    /**
     * 售后详情
     * @return \think\response\Json
     * oi_id   订单详情ID
     */
    public function afterSaleDetail(){
        $oi_id = input('oi_id');
        $detail = Db::table('up_order_info')
            ->join('up_return ur', 'ur.exchange_id = after_return_id', 'left')
            ->join('up_exchange ue', 'ue.exchange_id = after_exchange_id', 'left')
            ->where('oi_id', $oi_id)
            ->field('oi_order_id, oi_price, oi_num, oi_good_name, oi_good_thumb, oi_type, 
            ur.exchange_name as return_name, ue.exchange_name, after_num, oi_after_status, 
            after_reason, oi_is_rerturn, after_user_courier, after_user_num, after_us_courier, 
            after_us_num, after_status')
            ->find();
        $order = Db::table('up_order')
            ->join('up_area ua1', 'ua1.district_id = order_sheng', 'left')
            ->join('up_area ua2', 'ua2.district_id = order_shi', 'left')
            ->join('up_area ua3', 'ua3.district_id = order_qu', 'left')
            ->where('order_id', $detail['oi_order_id'])
            ->field('order_name, order_address, order_phone, ua1.district as sheng, 
            ua2.district as shi, ua3.district as qu')
            ->find();
        $detail['order_name'] = $order['order_name'];
        $detail['order_address'] = $order['sheng'] . $order['shi'] . $order['qu'] . $order['order_address'];
        $detail['order_phone'] = $order['order_phone'];
        if($detail){
            return json(['status' => 200, 'msg' => $detail]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 提交物流
     * @return \think\response\Json
     * after_user_courier  物流公司
     * after_user_num   物流单号
     * oi_id    订单详情ID
     */
    public function express(){
        $oi_id = input('oi_id');
        $after_user_courier = trim(input('after_user_courier'), ' ');//物流公司
        $after_user_num = trim(input('after_user_num'), ' ');//物流单号
        Db::startTrans();
        try{
            Db::table('up_order_info')
                ->where('oi_id', $oi_id)
                ->update(['after_user_courier' => $after_user_courier, 'after_user_num' => $after_user_num]);
            Db::table('up_after_sale_time')
                ->insert([
                    'ast_after_oi_id' => $oi_id,
                    'ast_after_time' => $this->after_time,
                    'ast_after_content' => '物流单号已填写完毕，等待平台收货',
                ]);
            Db::commit();
            $res = 1;
        }catch(\Exception $e){
            Db::rollback();
            $res = 2;
        }
        
        if($res == 1){
            return json(['status' => 200, 'msg' => '提交成功']);
        }else{
            return json(['status' => 0, 'msg' => '提交失败']);
        }
    }
    
    /**
     * 售后时间轴
     * @return \think\response\Json
     * oi_id    消息详情ID
     */
    public function afterTimeShaft(){
        $oi_id = input('oi_id');
        $timeList = Db::table('up_after_sale_time')
            ->where('ast_after_oi_id', $oi_id)
            ->field('ast_after_time, ast_after_content')
            ->order('ast_after_time desc')
            ->select();
        if($timeList){
            return json(['status' => 200, 'msg' => $timeList]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
        
    }
    
    /**
     * 平台回寄信息
     * @return \think\response\Json
     */
    public function plat(){
        $plat = Db::table('up_plat')->where('plat_id', 1)->find();
        return json(['status' => 200, 'msg' => $plat]);
    }
}